package com.ygo.feihua;

import android.os.*;
import java.io.*;

import android.util.*;
import java.util.*;
import java.util.zip.*;
import com.file.zip.ZipEntry;
import com.file.zip.ZipFile;



/**
 * 解压zip文件的子线程
 * 需要权限：
 * <!-- SDCard中创建与删除文件权限 -->
 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
 <!-- SDCard写入数据权限 -->
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
 * 作者：cc
 * 日期：2015/10/7 0：53
 * **/
public class DecompressionZipThread extends Thread
{

	Handler handler;
	/** 源zip文件 **/
	String zipPath;
	/** 输出文件夹 **/
	String outPath;
	String ppth;
	boolean isaz;
	public static final int DEFAULT_BUFSIZE = 1024 * 16;

	public DecompressionZipThread(String zipPath, String outPath, Handler handler)
	{
		this.handler = handler;
		this.zipPath = zipPath;
		this.outPath = outPath;
		start();
	}
	void shwoTost(String s)
	{
		Message m=new Message();
		m.obj = s;
		m.what = 1;
		handler.sendMessage(m);
	}
	void updtatText(String s)
	{
		Message m=new Message();
		m.obj = s;
		m.what = 2;
		handler.sendMessage(m);
	}
	@Override
	public void run()
	{
		super.run();
		shwoTost("解压期间请勿退出这个界面以及软件");
        Message m=new Message();
        m.what = 8;
		handler.sendMessage(m);
        
		try
		{
			unzip(new File(zipPath), outPath);
		}
		catch (IOException e)
		{
			shwoTost("解压失败"+e);
		}
	}
	/*
	* @param file      待解压文件
	* @param dir       解压后文件的存放目录
	* @throws IOException
	*/
	public void unzip(File file, String dir) throws IOException {
		ZipFile zipFile = new ZipFile(file, "GBK");//设置压缩文件的编码方式为GBK
		Enumeration<ZipEntry> entris = zipFile.getEntries();
		ZipEntry zipEntry = null;
		File tmpFile = null;
		BufferedOutputStream bos = null;
		InputStream is = null;
		byte[] buf = new byte[1024];
		int len = 0;
		
		while (entris.hasMoreElements()) {
			zipEntry = entris.nextElement();
			// 不进行文件夹的处理,些为特殊处理
			tmpFile = new File(dir + zipEntry.getName());
			//显示解压目录
			updtatText(dir + zipEntry.getName());
			if(new File(dir + zipEntry.getName()).getName().endsWith(".apk")){
				isaz=true;
				ppth=dir + zipEntry.getName();
			}
			if (zipEntry.isDirectory()) {//当前文件为目录
				if (!tmpFile.exists()) {
					tmpFile.mkdir();
				}
			} else {
				if (!tmpFile.exists()) {
					tmpFile.createNewFile();
				}
				is = zipFile.getInputStream(zipEntry);
				bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
				while ((len = is.read(buf)) > 0) {
					bos.write(buf, 0, len);
				}
				bos.flush();
				bos.close();
					
			}
		}
		if(isaz){
			
			Message m=new Message();
			m.what = 11;
			m.obj=ppth;
			handler.sendMessage(m);
			
		}else{
		shwoTost("解压结束！将在两秒后退出~");
        Message m=new Message();
        m.what = 9;
        handler.sendMessage(m);
        
		try
		{
			sleep(2000);
		}
		catch (InterruptedException e)
		{}
		handler.sendEmptyMessage(3);
		}
	}
	




}
	
	

